<template>
  <el-dialog
    v-model="dialogVisible"
    title="调度计划详情"
    width="1200px"
    :close-on-click-modal="false"
  >
    <div class="dispatch-detail">
      <el-tabs type="border-card">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <div class="info-section">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="计划名称">
                <span class="plan-name">{{ dispatchData.planName }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="调度类型">
                <el-tag :type="getTypeTagType(dispatchData.dispatchType)" size="small">
                  {{ getTypeText(dispatchData.dispatchType) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="优先级">
                <el-tag :type="getPriorityTagType(dispatchData.priority)" size="small">
                  {{ getPriorityText(dispatchData.priority) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="执行状态">
                <el-tag :type="getStatusTagType(dispatchData.status)" size="small">
                  {{ getStatusText(dispatchData.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="计划执行时间">
                {{ formatDateTime(dispatchData.scheduledTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="实际开始时间">
                {{ formatDateTime(dispatchData.actualStartTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="执行进度">
                <el-progress
                  :percentage="dispatchData.progress || 0"
                  :status="dispatchData.progress === 100 ? 'success' : ''"
                  :stroke-width="8"
                />
              </el-descriptions-item>
              <el-descriptions-item label="预计持续时间">
                {{ dispatchData.estimatedDuration || 0 }} 小时
              </el-descriptions-item>
              <el-descriptions-item label="创建人">
                {{ dispatchData.creator }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDateTime(dispatchData.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="调度范围" :span="2">
                <el-tag
                  v-for="scope in (dispatchData.scope || [])"
                  :key="scope"
                  size="small"
                  style="margin-right: 8px"
                >
                  {{ scope }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="计划描述" :span="2">
                {{ dispatchData.description || '暂无描述' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <!-- 调度参数 -->
        <el-tab-pane label="调度参数" name="parameters">
          <div class="parameters-section">
            <!-- 水位控制参数 -->
            <div class="parameter-group">
              <h4>水位控制参数</h4>
              <el-descriptions :column="3" border>
                <el-descriptions-item label="目标水位">
                  {{ dispatchData.parameters?.targetWaterLevel || 0 }} m
                </el-descriptions-item>
                <el-descriptions-item label="最高水位">
                  {{ dispatchData.parameters?.maxWaterLevel || 0 }} m
                </el-descriptions-item>
                <el-descriptions-item label="最低水位">
                  {{ dispatchData.parameters?.minWaterLevel || 0 }} m
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 流量控制参数 -->
            <div class="parameter-group">
              <h4>流量控制参数</h4>
              <el-descriptions :column="3" border>
                <el-descriptions-item label="目标流量">
                  {{ dispatchData.parameters?.targetFlow || 0 }} m³/s
                </el-descriptions-item>
                <el-descriptions-item label="最大流量">
                  {{ dispatchData.parameters?.maxFlow || 0 }} m³/s
                </el-descriptions-item>
                <el-descriptions-item label="最小流量">
                  {{ dispatchData.parameters?.minFlow || 0 }} m³/s
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 闸门控制参数 -->
            <div class="parameter-group">
              <h4>闸门控制参数</h4>
              <el-table
                :data="dispatchData.parameters?.gates || []"
                border
                style="width: 100%"
              >
                <el-table-column prop="name" label="闸门名称" width="200" />
                <el-table-column prop="openingDegree" label="开度(%)" width="120">
                  <template #default="{ row }">
                    {{ row.openingDegree }}%
                  </template>
                </el-table-column>
                <el-table-column prop="flow" label="流量(m³/s)" width="150">
                  <template #default="{ row }">
                    {{ row.flow }} m³/s
                  </template>
                </el-table-column>
                <el-table-column prop="mode" label="控制模式">
                  <template #default="{ row }">
                    <el-tag :type="getModeTagType(row.mode)" size="small">
                      {{ getModeText(row.mode) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 执行步骤 -->
        <el-tab-pane label="执行步骤" name="steps">
          <div class="steps-section">
            <div class="steps-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(step, index) in dispatchData.steps || []"
                  :key="index"
                  :type="getStepTimelineType(step.status)"
                  :icon="getStepIcon(step.status)"
                  size="large"
                >
                  <div class="step-content">
                    <div class="step-header">
                      <h4>{{ step.name }}</h4>
                      <el-tag :type="getStepTagType(step.type)" size="small">
                        {{ getStepTypeText(step.type) }}
                      </el-tag>
                    </div>
                    
                    <div class="step-info">
                      <el-row :gutter="20">
                        <el-col :span="8">
                          <div class="info-item">
                            <span class="label">负责人：</span>
                            <span class="value">{{ step.responsible }}</span>
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="info-item">
                            <span class="label">预计时长：</span>
                            <span class="value">{{ step.estimatedTime }} 分钟</span>
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="info-item">
                            <span class="label">是否必需：</span>
                            <el-tag :type="step.required ? 'danger' : 'info'" size="small">
                              {{ step.required ? '必需' : '可选' }}
                            </el-tag>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                    
                    <div v-if="step.description" class="step-description">
                      <span class="label">步骤描述：</span>
                      <span class="value">{{ step.description }}</span>
                    </div>
                    
                    <div v-if="step.conditions" class="step-conditions">
                      <span class="label">执行条件：</span>
                      <span class="value">{{ step.conditions }}</span>
                    </div>
                    
                    <div v-if="step.status" class="step-status">
                      <el-tag :type="getStepStatusTagType(step.status)" size="small">
                        {{ getStepStatusText(step.status) }}
                      </el-tag>
                      <span v-if="step.completedTime" class="completed-time">
                        完成时间：{{ formatDateTime(step.completedTime) }}
                      </span>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-tab-pane>

        <!-- 相关人员 -->
        <el-tab-pane label="相关人员" name="personnel">
          <div class="personnel-section">
            <el-row :gutter="40">
              <el-col :span="12">
                <div class="personnel-group">
                  <h4>通知人员</h4>
                  <div class="personnel-list">
                    <el-tag
                      v-for="person in getPersonnelList(dispatchData.notificationPersonnel)"
                      :key="person.key"
                      size="large"
                      style="margin: 5px"
                    >
                      {{ person.label }}
                    </el-tag>
                    <div v-if="!dispatchData.notificationPersonnel?.length" class="empty-text">
                      暂无通知人员
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="personnel-group">
                  <h4>执行人员</h4>
                  <div class="personnel-list">
                    <el-tag
                      v-for="person in getPersonnelList(dispatchData.executionPersonnel)"
                      :key="person.key"
                      size="large"
                      style="margin: 5px"
                      type="success"
                    >
                      {{ person.label }}
                    </el-tag>
                    <div v-if="!dispatchData.executionPersonnel?.length" class="empty-text">
                      暂无执行人员
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 执行历史 -->
        <el-tab-pane label="执行历史" name="history">
          <div class="history-section">
            <div class="history-header">
              <h4>执行历史记录</h4>
              <el-button type="primary" size="small" @click="refreshHistory">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
            
            <el-table :data="executionHistory" border style="width: 100%">
              <el-table-column prop="executionTime" label="执行时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.executionTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="executor" label="执行人" width="120" />
              <el-table-column prop="action" label="执行动作" width="150" />
              <el-table-column prop="status" label="执行状态" width="120">
                <template #default="{ row }">
                  <el-tag :type="getExecutionStatusTagType(row.status)" size="small">
                    {{ getExecutionStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="耗时" width="100">
                <template #default="{ row }">
                  {{ row.duration }} 分钟
                </template>
              </el-table-column>
              <el-table-column prop="result" label="执行结果" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewHistoryDetail(row)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 附件信息 -->
        <el-tab-pane label="附件信息" name="attachments">
          <div class="attachments-section">
            <div v-if="dispatchData.attachments?.length > 0">
              <h4>相关附件</h4>
              <el-table :data="dispatchData.attachments" border style="width: 100%">
                <el-table-column prop="name" label="文件名" />
                <el-table-column prop="size" label="文件大小" width="120">
                  <template #default="{ row }">
                    {{ formatFileSize(row.size) }}
                  </template>
                </el-table-column>
                <el-table-column prop="uploadTime" label="上传时间" width="180">
                  <template #default="{ row }">
                    {{ formatDateTime(row.uploadTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="downloadFile(row)">
                      <el-icon><Download /></el-icon>
                      下载
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="empty-attachments">
              <el-empty description="暂无附件" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="success" @click="editPlan" :disabled="dispatchData.status === 'executing'">
          编辑
        </el-button>
        <el-button
          type="warning"
          @click="executePlan"
          :disabled="dispatchData.status === 'executing' || dispatchData.status === 'completed'"
        >
          执行
        </el-button>
        <el-button type="primary" @click="exportPlan">
          导出
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download, CircleCheck, Clock, Warning } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  dispatchData: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'edit', data: any): void
  (e: 'execute', data: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  dispatchData: () => ({})
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 执行历史数据
const executionHistory = ref([
  {
    id: 1,
    executionTime: '2024-03-15 08:05:00',
    executor: '张三',
    action: '启动调度计划',
    status: 'success',
    duration: 2,
    result: '调度计划启动成功'
  },
  {
    id: 2,
    executionTime: '2024-03-15 08:30:00',
    executor: '李四',
    action: '调整闸门开度',
    status: 'success',
    duration: 15,
    result: '闸门开度调整至65%'
  },
  {
    id: 3,
    executionTime: '2024-03-15 09:00:00',
    executor: '王五',
    action: '监测水位变化',
    status: 'running',
    duration: 0,
    result: '正在监测中...'
  }
])

// 可选人员数据
const availablePersonnel = [
  { key: 1, label: '张三 - 调度员' },
  { key: 2, label: '李四 - 工程师' },
  { key: 3, label: '王五 - 技术员' },
  { key: 4, label: '赵六 - 监测员' },
  { key: 5, label: '孙七 - 维护员' },
  { key: 6, label: '周八 - 安全员' },
  { key: 7, label: '吴九 - 主管' },
  { key: 8, label: '郑十 - 副主管' }
]

// 获取人员列表
const getPersonnelList = (personnelIds: number[]) => {
  if (!personnelIds || !Array.isArray(personnelIds)) return []
  return availablePersonnel.filter(person => personnelIds.includes(person.key))
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    'flood-control': 'danger',
    'water-supply': 'primary',
    'power-generation': 'warning',
    'ecological': 'success',
    'comprehensive': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const textMap = {
    'flood-control': '防洪调度',
    'water-supply': '供水调度',
    'power-generation': '发电调度',
    'ecological': '生态调度',
    'comprehensive': '综合调度'
  }
  return textMap[type] || type
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const typeMap = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger',
    'urgent': 'danger'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'urgent': '紧急'
  }
  return textMap[priority] || priority
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap = {
    'pending': 'info',
    'executing': 'warning',
    'completed': 'success',
    'paused': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    'pending': '待执行',
    'executing': '执行中',
    'completed': '已完成',
    'paused': '已暂停',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 获取模式标签类型
const getModeTagType = (mode: string) => {
  const typeMap = {
    'auto': 'success',
    'manual': 'warning',
    'remote': 'primary'
  }
  return typeMap[mode] || 'info'
}

// 获取模式文本
const getModeText = (mode: string) => {
  const textMap = {
    'auto': '自动',
    'manual': '手动',
    'remote': '远程'
  }
  return textMap[mode] || mode
}

// 获取步骤时间线类型
const getStepTimelineType = (status: string) => {
  const typeMap = {
    'completed': 'success',
    'running': 'warning',
    'pending': 'info',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取步骤图标
const getStepIcon = (status: string) => {
  const iconMap = {
    'completed': CircleCheck,
    'running': Clock,
    'pending': Clock,
    'failed': Warning
  }
  return iconMap[status] || Clock
}

// 获取步骤标签类型
const getStepTagType = (type: string) => {
  const typeMap = {
    'water-level': 'primary',
    'flow-control': 'success',
    'gate-operation': 'warning',
    'pump-operation': 'info',
    'monitoring': 'success',
    'manual-confirm': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取步骤类型文本
const getStepTypeText = (type: string) => {
  const textMap = {
    'water-level': '水位调节',
    'flow-control': '流量控制',
    'gate-operation': '闸门操作',
    'pump-operation': '泵站启停',
    'monitoring': '监测检查',
    'manual-confirm': '人工确认'
  }
  return textMap[type] || type
}

// 获取步骤状态标签类型
const getStepStatusTagType = (status: string) => {
  const typeMap = {
    'completed': 'success',
    'running': 'warning',
    'pending': 'info',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取步骤状态文本
const getStepStatusText = (status: string) => {
  const textMap = {
    'completed': '已完成',
    'running': '执行中',
    'pending': '待执行',
    'failed': '执行失败'
  }
  return textMap[status] || status
}

// 获取执行状态标签类型
const getExecutionStatusTagType = (status: string) => {
  const typeMap = {
    'success': 'success',
    'running': 'warning',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取执行状态文本
const getExecutionStatusText = (status: string) => {
  const textMap = {
    'success': '成功',
    'running': '执行中',
    'failed': '失败'
  }
  return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '-'
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 刷新执行历史
const refreshHistory = () => {
  ElMessage.success('执行历史已刷新')
}

// 查看历史详情
const viewHistoryDetail = (row: any) => {
  ElMessage.info(`查看执行历史详情: ${row.action}`)
}

// 下载文件
const downloadFile = (file: any) => {
  ElMessage.success(`开始下载文件: ${file.name}`)
}

// 编辑计划
const editPlan = () => {
  emit('edit', props.dispatchData)
}

// 执行计划
const executePlan = () => {
  emit('execute', props.dispatchData)
}

// 导出计划
const exportPlan = () => {
  ElMessage.success('导出功能开发中...')
}
</script>

<style scoped>
.dispatch-detail {
  max-height: 600px;
  overflow-y: auto;
}

.info-section {
  padding: 20px;
}

.plan-name {
  font-weight: 600;
  color: #409eff;
}

.parameters-section {
  padding: 20px;
}

.parameter-group {
  margin-bottom: 30px;
}

.parameter-group h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.steps-section {
  padding: 20px;
}

.steps-timeline {
  max-height: 500px;
  overflow-y: auto;
}

.step-content {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.step-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.step-info {
  margin-bottom: 15px;
}

.info-item {
  margin-bottom: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #666;
}

.info-item .value {
  color: #333;
}

.step-description,
.step-conditions {
  margin-bottom: 10px;
}

.step-description .label,
.step-conditions .label {
  font-weight: 500;
  color: #666;
}

.step-description .value,
.step-conditions .value {
  color: #333;
}

.step-status {
  display: flex;
  align-items: center;
  gap: 15px;
}

.completed-time {
  font-size: 12px;
  color: #666;
}

.personnel-section {
  padding: 20px;
}

.personnel-group {
  margin-bottom: 30px;
}

.personnel-group h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.personnel-list {
  min-height: 60px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.empty-text {
  color: #999;
  text-align: center;
  padding: 20px 0;
}

.history-section {
  padding: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.attachments-section {
  padding: 20px;
}

.attachments-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.empty-attachments {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

:deep(.el-timeline-item__content) {
  padding-bottom: 30px;
}
</style>